package com.example.equipmentmanage

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ImageDecoder
import android.graphics.Paint
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.equipmentmanage.databinding.ActivitySheBeiAddBinding
import com.example.equipmentmanage.utils.SheBeiViewModel
import com.example.lib_base.mvvm.BaseActivity
import dagger.hilt.android.AndroidEntryPoint
import okio.IOException
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@Route(path = "/equipmentmanage/SheBeiAddActivity")
@AndroidEntryPoint
class SheBeiAddActivity : BaseActivity<ActivitySheBeiAddBinding,SheBeiViewModel>() {
    val areaitems = listOf("门禁设备", "监控设备","水龙头设备","其他设备")
    val areastate = listOf("正常", "故障")
    private var id: Int = 149
    private val REQUEST_GALLERY = 100
    private val REQUEST_CAMERA = 101
    private val REQUEST_PERMISSIONS = 102

    private lateinit var imageView: ImageView
    private var currentPhotoPath: String? = null

    override fun initView() {
        imageView = binding.btnAddPhoto // 假设你的布局里有一个 ImageView 用于显示图片

        binding.back.setOnClickListener {
            finish()
        }
        //区域选择
        val areaadapter = ArrayAdapter(this,android.R.layout.simple_spinner_item,areaitems).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        binding.spinnerWorkOrderType.adapter = areaadapter
        binding.spinnerWorkOrderType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有选项被选中时触发
            }


        }

        //从相册中选择照片
        binding.btnAddPhoto.setOnClickListener {
            // 从相册选择照片
            if (checkPermissions()) {
                openGallery()
            } else {
                requestPermissions()
            }

        }
        //状态选择
        val areaadapter2 = ArrayAdapter(this,android.R.layout.simple_spinner_item,areastate).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        binding.spinnerReserveTime.adapter = areaadapter2
        binding.spinnerReserveTime.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有选项被选中时触发
            }
        }
        binding.btnSubmit.setOnClickListener {
            val map = mutableMapOf<String, Any?>()
            map["id"]=id
            map["deviceName"]=binding.etName.text.toString()
            map["deviceType"]=binding.spinnerWorkOrderType.selectedItem.toString()
            map["installationLocation"]=binding.etAddress.text.toString()
            map["failureRate"]=binding.etWorkOrderContent.text.toString().toDouble()
            map["status"]=binding.spinnerReserveTime.selectedItem.toString()
            vm.SheAdd(map)
            }
//            "id": 149,
//            "deviceName": "门禁设备A",
//            "deviceType": "门禁设备",
//            "installationLocation": "南门",
//            "failureRate": 0.2,
//            "status": "正常"

        }

    override fun initData() {
        vm.SheAddSuccess.observe(this){
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show()
            finish()
        }
    }


    // 检查权限
    private fun checkPermissions(): Boolean {
        val readPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
        } else {
            ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        }

        val cameraPermission = ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED

        return readPermission && cameraPermission
    }
    // 请求权限
    private fun requestPermissions() {
        val permissions = mutableListOf<String>()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.READ_MEDIA_IMAGES)
            }
        } else {
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }

        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(android.Manifest.permission.CAMERA)
        }

        ActivityCompat.requestPermissions(this, permissions.toTypedArray(), REQUEST_PERMISSIONS)
    }
    // 打开相册
    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_GALLERY)
    }

// ...existing code...

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_GALLERY && resultCode == Activity.RESULT_OK && data != null) {
            val selectedImage: Uri? = data.data
            if (selectedImage != null) {
                imageView.setImageURI(selectedImage)
                // 如果你想把图片显示到按钮上，可以用 btnAddPhoto.background = BitmapDrawable(resources, bitmap)
            }
        }
    }



}